package com.xiaochong.bitong.api.webWs;

import com.xiaochong.bitong.api.utils.ApiVersion;
import com.xiaochong.bitong.api.utils.SpringContextUtil;
import com.xiaochong.service.common.config.redis.RedisServer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @Description: 根据交易所id和交易对获取交易对价格等数据
 * @Author: org
 * @CreateDate: 2018/8/9 19:13
 */
@Component
@ServerEndpoint(value = ApiVersion.API_V1_PREFIX+"/initExchangePairListAppWs")
public class InitExchangePairListWS {
    //private Integer exchangeId;
    private String transactionName= "exchange";
    @Autowired
    private RedisServer redisServer;

    AsyncWsPush asyncWsPush;
    public static final Logger logger = LoggerFactory.getLogger(InitExchangePairListWS.class);
    @OnOpen
    public void onOpen(Session session) {
       // this.exchangeId = exchangeId;
        logger.info("开始打开一个连接"+session.getId());
        WsSessionContainer.addSession( session,"initExchangePairListAppWs","pair",System.currentTimeMillis());
    }
    @OnMessage
    public void onMessage(String message, Session session){
        try {
            if(asyncWsPush == null && StringUtils.isNotBlank(message)){
                AsyncWsPush asyncWsPush = (AsyncWsPush) SpringContextUtil.getBean("AsyncWsPush");
                asyncWsPush.pairDataList(session,message);
                WsSessionContainer.addSessionDatetime(session,System.currentTimeMillis());
            }
        }catch (Exception e){
            e.printStackTrace();
            //logger.info("exchangeId",exchangeId+"-"+transactionName);
            logger.error(e.getMessage() , e);
        }
    }
    @OnError
    public void error(Throwable t) {
        logger.info("连接错误:" + t.getMessage());
        t.printStackTrace();
        logger.error(t.getMessage(),t);
    }

    @OnClose
    public void close(Session session) {
        WsSessionContainer.removeSession(session,"initExchangePairListAppWs","pair");
        logger.error(session.getId()+transactionName+"断开连接");
    }
}
